import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

public class OutputStreamExample {

	private static void createRandomFileByteByByte() throws IOException {
		OutputStream outputStream = new FileOutputStream("slow.bin");
		try {
			Random rand = new Random();
			for (int i = 0; i < 5 * 1024 * 1024; i++) {
				byte randomByte = (byte) rand.nextInt(256);
				outputStream.write(randomByte);
			}
		} finally {
			outputStream.close();
		}
	}

	private static void createRandomFileWithBuf() throws IOException {
		byte[] buf = new byte[1024 * 1024];
		OutputStream outputStream = new FileOutputStream("fast.bin");
		try {
			Random rand = new Random();
			for (int i = 0; i < 5; i++) {
				rand.nextBytes(buf);
				outputStream.write(buf);
			}
		} finally {
			outputStream.close();
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println("Writing 5 MB file byte by byte ...");
		long startTime = new Date().getTime();
		createRandomFileByteByByte();
		long endTime = new Date().getTime();
		System.out.printf("Execution time: %d ms.\n", endTime-startTime);
		
		System.out.println("Writing 5 MB file with a buffer ...");
		startTime = new Date().getTime();
		createRandomFileWithBuf();
		endTime = new Date().getTime();
		System.out.printf("Execution time: %d ms.\n", endTime-startTime);
	}

}
